package com.flitsneak.designpatterns.structuralpatterns.proxy.dynamicproxy.proxy;

import com.flitsneak.designpatterns.structuralpatterns.proxy.dynamicproxy.advice.PostAdvice;
import com.flitsneak.designpatterns.structuralpatterns.proxy.dynamicproxy.advice.PreAdvice;
import com.flitsneak.designpatterns.structuralpatterns.proxy.staticproxy.subject.Fruits;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/7/6 14:05
 * @description 运行时动态代理 买水果时动态指定对象
 */
public class DynamicFeiFeiProxy implements InvocationHandler {
    private Fruits fruits;

    public Fruits getFruits(Fruits fruits) {
        this.fruits = fruits;
        Class<?> clazz = fruits.getClass();
        return (Fruits) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (true) {
            (new PreAdvice()).weave();
        }
        Object res = method.invoke(this.fruits, args);
        if (true) {
            (new PostAdvice()).weave();
        }
        return res;
    }
}
